﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Revit;
using HYFamilyLibDataManager;
using HYView;
using ModelValidation.FireCompartment;
using ModelValidation.Utils;

namespace ModelValidation.Commands
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdCheckFMDimOrNot : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			Document document = cmdData.Application.ActiveUIDocument.Document;
			List<ViewPlan> lstViewPlan = new List<ViewPlan>();
			FloorSelectManager.CommandName = "CmdCheckFMDimOrNot";
			if (!FloorSelectManager.SelectAllFloorViewPlans(document, ref lstViewPlan))
			{
				return Autodesk.Revit.UI.Result.Succeeded;
			}
			Transaction transaction = null;
			Result result;
			try
			{
				if (cmdData == null)
				{
					throw new System.ArgumentNullException("commandData");
				}
				ViewPlanElemTreeViewForm viewPlanElemTreeViewForm = new ViewPlanElemTreeViewForm(cmdData, lstViewPlan, ViewPlanElemTreeViewForm.ECheckType.eCheckFireDoorHaveTagOrNot);
				if (viewPlanElemTreeViewForm.ShowDialog() == DialogResult.OK)
				{
					ElementId elementId = this.GetDoorTagIdInCurDoc(document, "门标记", "门标记");
					if (elementId == null)
					{
						elementId = this.GetDoorTagInDb(document);
					}
					transaction = new Transaction(document);
					transaction.Start("CheckFMDimOrNot");
					double num = AssistFunc.mmToFeet(100.0);
					List<NotDimedDoorWithView> selectedDoors = viewPlanElemTreeViewForm.GetSelectedDoors();
					foreach (NotDimedDoorWithView notDimedDoorWithView in selectedDoors)
					{
						num = num / 100.0 * (double)notDimedDoorWithView.inView.Scale;
						FamilyInstance door = notDimedDoorWithView.door;
						XYZ point = ((LocationPoint)door.Location).Point;
						door.Symbol.get_Parameter(BuiltInParameter.CASEWORK_WIDTH).AsDouble();
						double width = ((Wall)door.Host).Width;
						XYZ xyz = point + door.FacingOrientation * (this.GetTagHeightOffset(door.FacingOrientation, notDimedDoorWithView.inView) + width + num);
						IndependentTag independentTag = cmdData.Application.ActiveUIDocument.Document.Create.NewTag(notDimedDoorWithView.inView, door, false, 0, 0, xyz);
						if (elementId != null)
						{
							independentTag.ChangeTypeId(elementId);
						}
					}
					MessageBox.Show("完成" + selectedDoors.Count.ToString() + "樘防火门标注");
					transaction.Commit();
				}
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				msg = ex.Message;
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

		private double GetTagHeightOffset(XYZ facingOrientation, Autodesk.Revit.DB.View view)
		{
			double num = AssistFunc.mmToFeet(100.0);
			num = num / 100.0 * (double)view.Scale;
			double num2 = Geometry.getAngle(XYZ.Zero, facingOrientation);
			num2 = Geometry.formatAngle(num2 + Math.PI*.5);
			if (Geometry.GreaterThan(num2, Math.PI*.5) && Geometry.Lessthan_Or_Equal(num2, 4.71238898038469))
			{
				return num;
			}
			return -num;
		}

		private ElementId GetDoorTagIdInCurDoc(Autodesk.Revit.DB.Document doc, string familyName, string symbolName)
		{
			foreach (Element element in new FilteredElementCollector(doc).OfClass(typeof(Family)).ToElements())
			{
				Family family = element as Family;
				if (family != null)
				{
					Category familyCategory = RevitVersionFuncs.GetFamilyCategory(family);
					if (familyCategory != null && familyName.ToUpper().CompareTo(family.Name.ToUpper()) == 0)
					{
						foreach (FamilySymbol familySymbol in family.GetSymbols())
						{
							if (symbolName.ToUpper().CompareTo(familySymbol.Name.ToUpper()) == 0)
							{
								return familySymbol.Id;
							}
						}
					}
				}
			}
			return null;
		}

		private ElementId GetDoorTagInDb(Autodesk.Revit.DB.Document doc)
		{
			foreach (DbCategory dbCategory in FamilyLibDatabase.GetSqliteDB(SubjectType.System, doc.Application.VersionNumber).CategoryTable.GetAll())
			{
				if (dbCategory.Name == "门标记")
				{
					foreach (DbFamily dbFamily in dbCategory.GetAllFamilies(false, CheckType.All))
					{
						List<FamilySymbol> symbols = dbFamily.Load(doc).GetSymbols();
						if (symbols.Count > 0)
						{
							FamilySymbol familySymbol = symbols[0];
							if (familySymbol != null)
							{
								return familySymbol.Id;
							}
						}
					}
				}
			}
			return null;
		}
	}
}
